<?php
/**
 * Lib\Pidguin\Error - error handler
 *
 * @author Eni
 * @version 0.1.1
 */
class Pidguin_Error
{
	/**
	 * Exception object
	 *
	 * @var Exception
	 */
	protected $_exception = null;
	/**
	 * Instance of class
	 *
	 * @var Pidguin_Error
	 */
	private static $_instance = null;
	
	/**
	 * Get instance of class
	 *
	 * @return Pidguin_Error
	 */
	public static function getInstance()
	{
		if (self::$_instance === null) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}
	
	/**
	 * Set odject exception
	 *
	 * @param object Exception $e
	 * @return this
	 */
	public function setException($e)
	{
		if (!$e instanceof Exception) {
			throw new Exception('Parameter should be the object of Exception');
		}
		$this->_exception = $e;
		return $this;
	}
	
	/**
	 * Set error handler
	 *
	 * @return void
	 */
	public function setErrorHandler()
	{
		set_error_handler(array($this, 'errorHandler'));
	}
	
	/**
	 * @return ErrorException
	 */
	public function errorHandler($errNo, $errStr, $errFile, $errLine)
	{
		if (!($errNo & error_reporting())) {
			return false;
		}
		throw new ErrorException($errStr, 0, $errNo, $errFile, $errLine);
		return true;
	}
	
	/**
	 * Renderer error
	 *
	 * @return string
	 */
	public function renderError()
	{
		$templatePath = LIB_DIR . DS . 'Pidguin' . DS . 'Error' . DS . 'Template' . DS . 'main.html';
		if (!is_file($templatePath)) {
			throw new Exception('Template error not found');
		}
		ob_start();
		$exception = $this->_exception;
		include $templatePath;
		$output = ob_get_contents();
		ob_end_clean();
		echo $output;
	}
}